// pages/care/publish/publish.js
import { GetElderlyCarePlanMission,SaveElderlyCareRecord } from '../../../apis/modules/elderly'
const uploadManager = require('../../../apis/base/file-upload.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 录音相关
    recorderManager: null,
    innerAudioContext: null,
    recordingPopup: false,
    recordingImageClass: "",
    recordStatus: "待录制",
    recordPlayStatus: "播放中",
    recordButtomText: "长安录音，松开停止",
    recordFile:{
        duration:0,
        fileSize:0,
        tempFilePath:null,
        durationSecond:0
    },
    // 老人信息相关
    elderlyId:0,
    elderlyName:'',
    // 照护项目相关
    mission:{

    },
    // 发布记录类容相关
    recordContent:"",
    recordMp3FilePlayId:0,
    recordMp3FileList:[],
    recordMp3DeleteFileList:[],
    recordImageFileList:[],
    recordImageDeleteFileList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({elderlyId:options.elderlyId,elderlyName:options.elderlyName})
    this.LoadElderlyCarePlanMission(options.mId);
    this.listenRecordingEvent();
  },
  // 加载照护计划动作内容
  LoadElderlyCarePlanMission:function(elderlyCarePlanMissionId){
    GetElderlyCarePlanMission(elderlyCarePlanMissionId).then(res=>{
        this.setData({mission:res.data})
    })
  },
  recordContentInputEvent:function(e){
    this.setData({recordContent:e.detail.value});
  },

  //  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  //  - - - - - - - - - - - - - - - - 录音相关开始 - - - - - - - - - - - - - - 
  //  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // 显示录音弹窗界面
  clickRecorderEvent:function(){
    const that=this;
    wx.authorize({
        scope: 'scope.record',
        success() { 
            that.setData({recordingPopup:true});
         },
        fail() { 
            wx.showToast({
                title: '请在右上角小程序设置中开启麦克风权限',
                icon:'none',
                duration: 3000
              })
         }
    });
  },
  // 关闭录音弹窗界面
  onCloseRecordingPopupEvent:function(){
    this.setData({recordingPopup:false});
  },
  // 开始录音
  startRecordingEvent:function(){
    this.setData({recordingImageClass:"recordIng",recordStatus:'录制中'});
       // 录音配置选项
       const options = {
        duration: 1200000,      // 录音时长，单位ms，默认1分钟
        sampleRate: 44100,     // 采样率
        numberOfChannels: 1,   // 录音通道数
        encodeBitRate: 192000, // 编码码率
        format: 'mp3'          // 音频格式，可选 'aac' / 'mp3'
      };
      this.recorderManager.start(options);
  },
  // 停止录音
  endRecordingEvent:function(){
    this.setData({recordingImageClass:"",recordStatus:'录制完成'});
    this.recorderManager.stop();
  },
  // 监听录音事件
  listenRecordingEvent:function(){
     // 初始化录音管理器并设置监听
     this.recorderManager = wx.getRecorderManager();
     // 监听录音停止事件
    this.recorderManager.onStop((res) => {
        res.durationSecond=(res.duration/1000).toFixed(2);
        this.setData({recordFile:res,recordButtomText:"长按录音，可以重新录制哦"});
        // 播放录音
        this.playRecordEvent();
    });
  },
  // 播放录音
  playRecordEvent:function(){
    if(this.innerAudioContext==null){
        const innerAudioContext = wx.createInnerAudioContext({
            useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
        })
        this.setData({innerAudioContext:innerAudioContext});
    }
    this.data.innerAudioContext.src = this.data.recordFile.tempFilePath;
    this.data.innerAudioContext.play();
    this.setData({recordPlayStatus:"播放中"});
    const that=this;
    setTimeout(function(){
        that.setData({recordPlayStatus:"播放完成",recordMp3FilePlayId:0});
    },this.data.recordFile.duration)
  },
  // 上传录音
  uploadRecordMp3File: function(){
    var that=this;
    wx.showLoading({
      title: '上传中',
    })
    uploadManager.upload({
        filePath: this.data.recordFile.tempFilePath,
        formData: {
            fileTag: "照护记录语音",
            durationSecond: this.data.recordFile.durationSecond
        },
        success: (data) => {
            let recordMp3FileList=that.data.recordMp3FileList;
            recordMp3FileList.push({
                durationSecond:data.durationSecond,
                fileId:data.fileId,
                fileUrl:data.fileUrl,
                mp3Text:data.mp3Text
            });
            that.setData({
                recordMp3FileList:recordMp3FileList,
                recordingPopup:false,
                recordStatus:"待录制"
            });
            wx.hideLoading();
        },
        fail: (error) => {
            console.log("上传失败",error);
            wx.hideLoading();
        }
    })
  },
  //  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
  //  - - - - - - - - - - - - - - - - 录音相关结束 - - - - - - - - - - - - - - 
  //  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  // 播放语音列表中的文件
  clickPlayMp3ListItemFileEvent:function(e){
    const mp3file=e.currentTarget.dataset.mp3file;
    const mp3fileindex=e.currentTarget.dataset.mp3fileindex;
    const recordFile={
        tempFilePath:mp3file.fileUrl,
        duration:mp3file.durationSecond*1000,
        durationSecond:mp3file.durationSecond,
        fileSize:0
    };
    this.setData({recordFile:recordFile,recordMp3FilePlayId:mp3file.fileId});
    this.playRecordEvent();
  },
  // 删除语音列表中的文件
  clickRemoveMp3ListItemFileEvent:function(e){
    console.log(e);
    const mp3file=e.currentTarget.dataset.mp3file;
    const mp3fileindex=e.currentTarget.dataset.mp3fileindex;
    let recordMp3FileList=this.data.recordMp3FileList;
    recordMp3FileList.splice(mp3fileindex,1);
    let recordMp3DeleteFileList=this.data.recordMp3DeleteFileList;
    recordMp3DeleteFileList.push(mp3file);
    this.setData({recordMp3FileList:recordMp3FileList,recordMp3DeleteFileList:recordMp3DeleteFileList});
  },

  // 点击拍照打卡,唤起摄像头拍摄
  clickTakePhotoEvent:function(){
    var that=this;
    wx.chooseMedia({
        count: 20,
        mediaType: ['image'],
        sourceType: ['camera'],
        sizeType:['compressed'],
        camera: 'back',
        success(res) {
            let id=Date.now();
            for (let index = 0; index < res.tempFiles.length; index++) {
                const tempFile = res.tempFiles[index];
                tempFile.fileId=id+index;
                that.uploadImageFile(tempFile);
            }
        }
    })
  },
  // 上传图片
  uploadImageFile:function(tempFile){
    console.log(tempFile);
    
    const that=this;
    let recordImageFileList=that.data.recordImageFileList;
    recordImageFileList.push({
        fileId:tempFile.fileId,
        fileUrl:tempFile.tempFilePath,
        isUploadIng:true
    });
    that.setData({recordImageFileList:recordImageFileList});

    uploadManager.upload({
        filePath: tempFile.tempFilePath,
        formData: {
            fileTag: "照护记录图片"
        },
        success: (data) => {
           let list = that.data.recordImageFileList;
           for (let index = 0; index < list.length; index++) {
               const file = list[index];
               if(file.fileUrl==tempFile.tempFilePath){
                    file.fileId = data.fileId;
                    file.fileUrl=data.fileUrl;
                    file.isUploadIng=false;
                    break;
               }
           }
           that.setData({recordImageFileList:list});
        },
        fail: (error) => {
            console.log("上传失败",error);
        }
    })   
  },
  // 删除图片列表中的图片
  clickRemoveImageFileEvent:function(e){
    console.log(e);
    const img=e.currentTarget.dataset.img;
    const imgindex=e.currentTarget.dataset.imgindex;
    let recordImageFileList= this.data.recordImageFileList;
    recordImageFileList.splice(imgindex,1);
    let recordImageDeleteFileList=this.data.recordImageDeleteFileList;
    recordImageDeleteFileList.push(img);
    this.setData({recordImageFileList:recordImageFileList,recordImageDeleteFileList:recordImageDeleteFileList});
  },

  // 完成照护，保存照护记录
  savePublishEvent:function(){
    if(this.data.mission.isTakePhotos && this.data.recordImageFileList.length==0){
        wx.showToast({
          title: '请完成拍照打卡',
          icon:"none"
        })
        return;
    }
    if(this.data.recordImageFileList.filter(x=>x.isUploadIng).length>0){
        wx.showToast({
            title: '请等待图片上传完成',
            icon:"none"
          })
          return; 
    }
    var saveParams={
        careMissionId:this.data.mission.id,
        recordContent:this.data.recordContent,
        recordMp3FileList:this.data.recordMp3FileList,
        recordMp3DeleteFileList:this.data.recordMp3DeleteFileList,
        recordImageFileList:this.data.recordImageFileList,
        recordImageDeleteFileList:this.data.recordImageDeleteFileList
    };
    SaveElderlyCareRecord(saveParams).then(res=>{
        console.log(res);
        wx.showToast({
          title: '记录成功',
        })
        wx.switchTab({url: '/pages/care/care-index/care-index'})
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})